import NavBar from "../components/commons/navbar/NavBar.tsx";
import Footer from "../components/commons/Footer.tsx";
import logo from "../assets/mylib.png"
import '../styles/modules/register.css'
import {SetStateAction, useState} from "react";
import {baseUrl} from "../settings/Settings.ts";
import {useNavigate} from "react-router-dom";
import ToastNotification from "../components/commons/ToastNotification.tsx";
import * as bootstrap from "bootstrap";


const RegisterPage = () => {

    const [notification, setNotification] = useState<string | undefined>(null)
    const [firstName, setFirstName] = useState('');
    const [lastName, setLastName] = useState('');
    const [username, setUsername] = useState('');
    const [password, setPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [email, setEmail] = useState('');
    const [address, setAddress] = useState('');


    const handleFirstNameChange = (e: { target: { value: SetStateAction<string>; }; }) => {
        setFirstName(e.target.value);
    };

    const handleLastNameChange = (e: { target: { value: SetStateAction<string>; }; }) => {
        setLastName(e.target.value);
    };

    const handleUsernameChange = (e: { target: { value: SetStateAction<string>; }; }) => {
        setUsername(e.target.value);
    };

    const handlePasswordChange = (e: { target: { value: SetStateAction<string>; }; }) => {
        setPassword(e.target.value);
    };

    const handleConfirmPasswordChange = (e: { target: { value: SetStateAction<string>; }; }) => {
        setConfirmPassword(e.target.value);
    };

    const handleEmailChange = (e: { target: { value: SetStateAction<string>; }; }) => {
        setEmail(e.target.value);
    };

    const handleAddressChange = (e: { target: { value: SetStateAction<string>; }; }) => {
        setAddress(e.target.value);
    };


    const navigate = useNavigate()




    const fetchData = () => {
        console.log(username, password, firstName, lastName, email, address)
        const formData = {
            username: username,
            password: password,
            firstName: firstName,
            lastName: lastName,
            email: email,
            address: address,
            type: 'student'
        };

        fetch(`${baseUrl}/api/account/register`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
        })
            .then(response => {
                return response.json().then(data => ({ response, data }));
            })
            .then(({ response, data }) => {
                    setNotification(data.message)
                    triggerToast()

                    console.log(response.ok)

                    if (response.ok) {
                        setTimeout(() => {
                            navigate('/profile')
                        }, 4000); // wait for 4 seconds before navigating
                    }

                    console.log(data);
                    // handle response from server

            })
    };

    const toastLiveExample = document.getElementById('liveToast');

    const triggerToast = () => {
        const toastBootstrap = bootstrap.Toast.getOrCreateInstance(toastLiveExample);
        toastBootstrap.show();
    };


    return (


        <>
            <main className="vw-100 d-flex flex-nowrap">
                <ToastNotification message={notification}/>
                <NavBar/>
                <main className="overflow-y-scroll">
                    <div className="container w-75" id="container-form">
                        <div className="py-5 text-center">
                            <img className="d-block mx-auto mb-4" src={logo} alt=""
                                 width="57" height="57"/>
                            <h2 id="text-header">Registration form</h2>
                            <p className="lead">Please input all the data carefully</p>

                        </div>

                        <div className="row">

                            <div className="col-md-7 col-lg-8 mx-auto">
                                <h4 className="mb-3" id="text-account-info">
                                    <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" fill="currentColor"
                                         className="bi bi-person-fill me-2" viewBox="0 0 16 16">
                                        <path
                                            d="M3 14s-1 0-1-1 1-4 6-4 6 3 6 4-1 1-1 1zm5-6a3 3 0 1 0 0-6 3 3 0 0 0 0 6"/>
                                    </svg>
                                    Basic information
                                </h4>
                                <form id="registration-form" className="needs-validation">
                                    <div className="row g-3">
                                        <div className="col-sm-6">
                                            <label htmlFor="firstName" className="form-label">First name</label>
                                            <input type="text" className="form-control" id="firstName"
                                                   placeholder="Jake" value={firstName} required
                                                   onChange={handleFirstNameChange}/>
                                            <div className="invalid-feedback">
                                                Name cannot contain symbols that are not letters.
                                            </div>
                                        </div>

                                        <div className="col-sm-6">
                                            <label htmlFor="lastName" className="form-label">Last name</label>
                                            <input type="text" className="form-control" id="lastName" placeholder="Paul"
                                                   value={lastName} required onChange={handleLastNameChange}/>
                                            <div className="invalid-feedback">
                                                Last name cannot contain symbols that are not letters.
                                            </div>
                                        </div>

                                        <div className="col-12">
                                            <label htmlFor="username" className="form-label">Username</label>
                                            <div className="input-group has-validation">
                                                <span className="input-group-text">@</span>
                                                <input type="text" className="form-control" id="username"
                                                       placeholder="jakepaul" value={username}
                                                       onChange={handleUsernameChange}/>
                                                <div className="invalid-feedback">
                                                    Username already exists.
                                                </div>
                                            </div>
                                        </div>

                                        <div className="col-12">
                                            <label htmlFor="password" className="form-label">Password</label>
                                            <div className="input-group has-validation">
                                                <input type="password" className="form-control" id="password"
                                                       placeholder="********" value={password} required
                                                       onChange={handlePasswordChange}/>
                                                <div className="invalid-feedback">
                                                    Your password is required.
                                                </div>
                                            </div>
                                        </div>

                                        <div className="col-12">
                                            <label htmlFor="confirm-password" className="form-label">Confirm
                                                password</label>
                                            <div className="input-group has-validation">
                                                <input type="password" className="form-control" id="confirm-password"
                                                       placeholder="********" value={confirmPassword} required
                                                       onChange={handleConfirmPasswordChange}/>
                                                <div className="invalid-feedback">
                                                    Confirm the password.
                                                </div>
                                            </div>
                                        </div>

                                        <div className="col-12">
                                            <label htmlFor="email" className="form-label">Email <span
                                                className="text-body-secondary">(Optional)</span></label>
                                            <input type="email" className="form-control" id="email"
                                                   placeholder="you@example.com" value={email}
                                                   onChange={handleEmailChange}/>
                                            <div className="invalid-feedback">
                                                Please enter a valid email address for shipping updates.
                                            </div>
                                        </div>

                                        <div className="col-12">
                                            <label htmlFor="address" className="form-label">Address</label>
                                            <input type="text" className="form-control" id="address"
                                                   placeholder="1234 Main St" value={address}
                                                   onChange={handleAddressChange}/>
                                            <div className="invalid-feedback">
                                                Please enter your shipping address.
                                            </div>
                                        </div>



                                        <button
                                            className={"w-100 btn mt-4 mb-5 btn-primary btn-lg rounded-5 text-uppercase primary-button"}
                                            type="submit"
                                            onClick={(e) => {
                                                e.preventDefault()
                                                fetchData()
                                            }}
                                        >
                                            Continue
                                        </button>
                                    </div>
                                </form>

                            </div>
                        </div>


                    </div>
                    <Footer/>
                </main>
            </main>

        </>
    )
}


export default RegisterPage